package com.questionGenerator.controller;

import cn.hutool.core.bean.BeanUtil;
import com.questionGenerator.commom.constant.JwtClaimsConstant;
import com.questionGenerator.commom.utils.JwtUtil;
import com.questionGenerator.config.JwtConfig;
import com.questionGenerator.dto.req.UserLoginDTO;
import com.questionGenerator.dto.req.UserRegistryDTO;
import com.questionGenerator.model.UserDO;
import com.questionGenerator.service.UserService;
import com.questionGenerator.vo.UnifyResponseVO;
import com.questionGenerator.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: usagi
 * @Date: 2024/04/09/15:56
 * @Description:
 */
@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtConfig jwtConfig;

    @PostMapping("/login")
    public UnifyResponseVO<UserVO> login(@RequestBody UserLoginDTO userRegistryDTO) throws Exception {
        UserDO user = userService.userlogin(userRegistryDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getId());
        claims.put(JwtClaimsConstant.NAME,user.getUsername());
        String token = JwtUtil.createJWT(
                jwtConfig.getAdminSecretKey(),
                jwtConfig.getAdminTtl(),
                claims);
        log.info("token:{}",token);
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setToken(token);
        return new UnifyResponseVO("200", userVO);
    }

    @PostMapping("/register")
    public UnifyResponseVO<UserVO> save(@RequestBody UserRegistryDTO userRegistryDTO){
        return new UnifyResponseVO("200",userService.save(userRegistryDTO));
    }
}
